import 'dart:io';
import 'dart:typed_data';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:fate_blind_box/chat_view/circle_progress.dart';
import 'package:fate_blind_box/chat_view/dialog/utils.dart';
import 'package:fate_blind_box/config/app_style.dart';
import 'package:fate_blind_box/widget/photo_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'ahu_text.dart';

class ImageMessageView extends StatelessWidget {
  final EMImageMessageBody messageBody;
  final EMMessage message;
  final EMUserInfo? userInfo;

  const ImageMessageView({
    super.key,
    required this.messageBody,
    required this.message,
    this.userInfo,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onLongPress: (){
        PermissionUtil.showBottomDialog(context, () => ObjectUtil.isEmpty(messageBody.remotePath)
            ?saveLocImage(messageBody.localPath):saveNetImage(messageBody.remotePath!));
      },
      onTap: () {
        Get.to(PhotoPreview(
          galleryItems: [
            ObjectUtil.isEmpty(messageBody.remotePath)
                ? messageBody.localPath
                : messageBody.remotePath
          ],
          defaultImage: 0,
        ));
      },
      child: loadImage(message, messageBody),
    );
  }

  /// 进度winget
  Widget progressView(int pro) {
    if (pro == 0 || pro == 100) {
      return const SizedBox();
    } else {
      return SizedBox(
        width: 20.w,
        height: 20.w,
        child: CustomPaint(
          painter: CircleProgressBarPainter(
            progress: pro / 100,
            backgroundColor: Colors.transparent,
          ),
        ),
      );
    }
  }

  double widget() {
    // 长款都不为空
    if (messageBody.width != null && messageBody.height != null) {
      if (messageBody.width! > messageBody.height!) {
        return 141.w;
      } else {
        return 78.w;
      }
    } else {
      return 141.w;
    }
  }

  double height() {
    // 长款都不为空
    if (messageBody.width != null && messageBody.height != null) {
      if (messageBody.width! > messageBody.height!) {
        return 105.w;
      } else if (messageBody.width! < messageBody.height!) {
        return 140.w;
      } else {
        return 78.w;
      }
    } else {
      return 78.w;
    }
  }

  Widget loadImage(EMMessage msg, EMImageMessageBody message) {
    /// 网络照片为空 则加载本地图片
    if (ObjectUtil.isEmpty(message.remotePath)) {
      Map<String, dynamic>? map = msg.attributes;
      int pro = 0;
      if (map != null) {
        pro = map['progress'];
      }
      return InkWell(
        onTap: () {
          EasyLoading.showToast('图片加载中');
        },
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            progressView(pro),
            SizedBox(width: 2.w),
            ClipRRect(
              borderRadius: BorderRadius.circular(6.w),
              child: Image.file(
                File(message.localPath),
                fit: BoxFit.cover,
                height: height(),
                width: widget(),
              ),
            ),
          ],
        ),
      );
    } else {
      return groupWidget(msg,message);
    }
  }

  Widget groupWidget(EMMessage msg, EMImageMessageBody message) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // msg.direction==MessageDirection.RECEIVE ?personWidget():const SizedBox(),
        // SizedBox(height: msg.direction == MessageDirection.RECEIVE ?4.w:0),
        ClipRRect(
          borderRadius: BorderRadius.circular(6.w),
          child: CachedNetworkImage(
            imageUrl: '${message.remotePath}',
            fit: BoxFit.cover,
            errorWidget: (context, url, error) => const Icon(Icons.error),
            height: height(),
            width: widget(),
          ),
        ),
      ],
    );
  }

  /// 成员信息
  Widget personWidget() {
    if (userInfo?.gender == 2) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 2.w),
            margin: EdgeInsets.only(right: 4.w),
            decoration: BoxDecoration(
              color: '#FFF3FD'.stringToColor,
              borderRadius: BorderRadius.circular(8.w),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(width: 6.w),
                Image.asset(
                  'images/user/txl_woman_icon.png',
                  width: 12.w,
                  height: 12.w,
                ),
                SizedBox(width: 3.w),
                AhuText(
                  text:'${userInfo?.birth}',
                  fontSize: 12,
                  color: '#FE73CF'.stringToColor,
                  fontWeight: FontWeight.w400,
                ),
                SizedBox(width: 6.w),
              ],
            ),
          ),
          AhuText(
            text: '${userInfo?.nickName}',
            color: '#868686'.stringToColor,
            fontSize: 11,
            fontWeight: FontWeight.w400,
          )
        ],
      );
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Container(
          padding: EdgeInsets.symmetric(vertical: 2.w),
          margin: EdgeInsets.only(right: 4.w),
          decoration: BoxDecoration(
            color: '#F3F7FF'.stringToColor,
            borderRadius: BorderRadius.circular(8.w),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(width: 6.w),
              Image.asset(
                'images/user/txl_man_icon.png',
                width: 12.w,
                height: 12.w,
              ),
              SizedBox(width: 3.w),
              AhuText(
                text:'${userInfo?.birth}',
                fontSize: 12,
                color: '#739BFE'.stringToColor,
                fontWeight: FontWeight.w400,
              ),
              SizedBox(width: 6.w),
            ],
          ),
        ),
        AhuText(
          text: '${userInfo?.nickName}',
          color: '#868686'.stringToColor,
          fontSize: 11,
          fontWeight: FontWeight.w400,
        )
      ],
    );
  }

  /// 保存照片
  saveLocImage(String path)async{
    final result = await ImageGallerySaver.saveFile(path);
    if (result['isSuccess']) {
      EasyLoading.showToast('成功保存到相册中');
    } else {
      EasyLoading.showToast('保存失败');
    }
  }

  /// 保存网络照片
  saveNetImage(String path)async{
    var response = await Dio().get(path,
        options: Options(responseType: ResponseType.bytes));
    final result = await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
    // 判断ios还是android,故需要引入 import 'dart:io';
    if (result != null) {
      EasyLoading.showToast('成功保存到相册中');
    } else {
      EasyLoading.showToast('保存失败');
    }
  }
}
